package com.delaphone.fadmin.action;

import com.delaphone.fadmin.model.FAdmins;
import com.delaphone.fadmin.service.AdminService;
import com.delaphone.flocash.util.SecurityUtil;
import com.delaphone.flocash.web.util.Validate;
import com.opensymphony.xwork2.Action;

/**
 * Login Action Controller
 * @author dongtv
 */
public class AuthAction extends CoreAction {

    private String username;
    private String password;
    private String captcha;
    private AdminService adminService;

    public String checkLogin() throws Exception {
        //Step1: Validate
        if (Validate.isEmptyString(username)) {
            addFieldError("username", "*");
        }
        if (Validate.isEmptyString(password)) {
            addFieldError("password", "*");
        }
//        if (Validate.isEmptyString(captcha)) {
//            addFieldError("captcha", "*");
//        }
        if (!getFieldErrors().isEmpty()) {
            addActionError(getText("login.fields.missing"));
        }
        if (!getActionErrors().isEmpty()) {
            return Action.INPUT;
        }
//        String c = (String) session.getAttribute("Captcha");
//        if (c == null || !captcha.toLowerCase().equals(c.toLowerCase())) {
//            addActionError(getText("login.captcha.error"));
//            return Action.INPUT;
//        }
        //Step2: check username & password (will add later)
        FAdmins adminLogged = adminService.checkLogin(username, SecurityUtil.makePwd(password));
        if (adminLogged != null) {
            session.setAttribute("admin", adminLogged);
            return SUCCESS;
        } else {
            addActionError(getText("login.failed.warning"));
            return INPUT;
        }

    }

    public String doLogout() {
        try {
            session.setAttribute("admin", null);
            session.invalidate();
        } catch (Exception ex) {
        }
        return SUCCESS;
    }
    // <editor-fold defaultstate="collapsed" desc="get and set methods">

    public String getCaptcha() {
        return captcha;
    }

    public void setCaptcha(String captcha) {
        this.captcha = captcha;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public AdminService getAdminService() {
        return adminService;
    }

    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }
    // </editor-fold>
}
